package postgres;

import java.io.IOException;
import java.io.InputStream;

public class InputBuffer {
	
	private byte[] buffer;
	private int index;
	private int size;
	private InputStream stream;

	public InputBuffer(InputStream stream) {
		this.stream = stream;
		this.buffer = new byte[512];;
		this.index = 0;
		refill();
	}

	private void refill() {
		try {
			index = 0;
			size = stream.read(buffer);
			System.out.println("reading: " + size);
		} catch (IOException e) {
		}
	}

	public int get(int position, int size) {
		if (index >= this.size) refill();
		position /= 8;
		size /= 8;
		position += index;
		int value = 0;
		for (int i = 0; i < size; ++i) {
			value = (value << 8) | buffer[position + i];
		}
		return value;
	}
	
	public int position() {
		return index;
	}
	
	public void setPosition(int index) {
		this.index = index;
	}
	
	public byte getByte() {
		if (index >= size) refill();
		return buffer[index++];
	}

	public byte[] getBytes(int length) {
		if (length <= 0) return null;
		byte[] data = new byte[length];
		for (int i = 0; i < length; ++i) {
			data[i] = getByte();
		}
		return data;
	}

	public void skip(int size) {
		if (index >= this.size) refill();
		index += size / 8;
	}

	public int getInt(int size) {
		size /= 8;
		int value = 0;
		for (int i = 0; i < size; ++i) {
			value = (value << 8) | getByte();
		}
		return value;
	}

	public String getString() {
		StringBuffer value = new StringBuffer();
		while (buffer[index] != 0) {
			value.append((char)getByte());
		}
		++index;
		return value.toString();
	}

	public int[] getInts(int size, int length) {
		int[] data = new int[length];
		for (int i = 0; i < length; ++i) {
			data[i] = getInt(size);
		}
		return data;
	}

	public boolean atEnd() {
		return index >= size;
	}

}
